package master

import (
	"context"
	"time"

	"crontab/common"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// mongodb日志管理
type LogMgr struct {
	client        *mongo.Client
	logCollection *mongo.Collection
}

var (
	G_logMgr *LogMgr
)

func InitLogMgr() (err error) {
	var (
		client        *mongo.Client
		clientOptions *options.ClientOptions
	)

	G_config.MongodbUri = "mongodb://localhost:27017" // 示例 URI

	clientOptions = options.Client().ApplyURI(G_config.MongodbUri).SetConnectTimeout(time.Duration(G_config.MongodbConnectTimeout) * time.Millisecond)
	if client, err = mongo.Connect(context.TODO(), clientOptions); err != nil {
		return
	}

	// // 建立mongodb连接
	// if client, err = mongo.Connect(
	// 	context.TODO(),
	// 	G_config.MongodbUri,
	// 	clientopt.ConnectTimeout(time.Duration(G_config.MongodbConnectTimeout)*time.Millisecond)); err != nil {
	// 	return
	// }

	G_logMgr = &LogMgr{
		client:        client,
		logCollection: client.Database("cron").Collection("log"),
	}
	return
}

// 查看任务日志
func (logMgr *LogMgr) ListLog(name string, skip int, limit int) (logArr []*common.JobLog, err error) {
	var (
		filter  *common.JobLogFilter
		logSort *common.SortLogByStartTime
		cursor  *mongo.Cursor
		jobLog  *common.JobLog
		skip64  int64
		limit64 int64
	)

	skip64 = int64(skip)
	limit64 = int64(limit)
	// len(logArr)
	logArr = make([]*common.JobLog, 0)

	// 过滤条件
	filter = &common.JobLogFilter{JobName: name}

	// 按照任务开始时间倒排
	logSort = &common.SortLogByStartTime{SortOrder: -1}

	// 查询
	findOptions := options.FindOptions{
		Sort:  logSort,  // 假设 logSortKey 是你要排序的字段名，1 是升序，-1 是降序
		Skip:  &skip64,  // 注意：这里 skip 需要是 int64 类型
		Limit: &limit64, // 同样，limit 也需要是 int64 类型
	}
	if cursor, err = logMgr.logCollection.Find(context.TODO(), filter, &findOptions); err != nil {
		// if cursor, err = logMgr.logCollection.Find(context.TODO(), filter, findopt.Sort(logSort), findopt.Skip(int64(skip)), findopt.Limit(int64(limit))); err != nil {
		return
	}
	// 延迟释放游标
	defer cursor.Close(context.TODO())

	for cursor.Next(context.TODO()) {
		jobLog = &common.JobLog{}

		// 反序列化BSON
		if err = cursor.Decode(jobLog); err != nil {
			continue // 有日志不合法
		}

		logArr = append(logArr, jobLog)
	}
	return
}
